package inv.stask.beans;

import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.SortedSet;
import java.util.TreeSet;

public class Tags implements Serializable, Comparable<Tags> {
	private static final String DELIMITER = ", ";
	private static final String EMPTY_STRING = "";

	private static final long serialVersionUID = -2572361033077791199L;
	
	private String name;
	
	public Tags(){}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(name == null && obj == null)
			return true;
		
		if(name != null && obj instanceof String)
			return name.equals((String)obj);

		return false;
	}

	public int compareTo(Tags o) {
		if(o == null)
			return -1;
		if(o.getName() != null)
			return this.getName().compareTo(o.getName());
		
		if(o.getName() == null && this.getName() == null)
			return 0;
		
		return 1;
	}
	
	public static String exportToString(SortedSet<Tags> tagList){
		if(tagList == null || tagList.isEmpty())
			return EMPTY_STRING;
		
		boolean firstValue = true;
		Iterator<Tags> it = tagList.iterator();
		StringBuffer buff	= new StringBuffer(64);
		while(it.hasNext()){
			Tags tag = it.next();
			buff.append(tag.getName());
			
			if(firstValue)
				firstValue	= false;
			else
				buff.append(DELIMITER);
		}
		
		return buff.toString();

	}
	
	public static SortedSet<Tags> importFromString(String list){
		if(list != null){
			String[] tags = list.split(",");
			if(tags.length > 0){
				SortedSet<Tags> tagSet	= new TreeSet<Tags>();
				for(String value: tags){
					Tags tag	= new Tags();
					tag.setName(value.trim());
					tagSet.add(tag);
				}
				
				return tagSet;
			}
		}
		
		return null;
	}
}
